import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QWidget, QLabel, QFileDialog, QVBoxLayout, QSlider
from PySide6.QtCore import Qt
# 导入图片处理相关库 (pip install pillow)
from PIL import Image, ImageFilter, ImageQt
from PySide6.QtGui import QPixmap


class MyWindow(QWidget):
    def __init__(self) -> None:
        super().__init__()

        self.setWindowTitle("02_读取展示图片_模糊")

        self.btn = QPushButton('点我导入图片')
        self.btn.clicked.connect(self.setImg)

        self.lbShowImg = QLabel()
        self.slider = QSlider(Qt.Orientation.Horizontal)
        self.slider.setRange(0, 20)
        self.slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        self.slider.setTickInterval(2)
        self.slider.valueChanged.connect(self.sliderValueChanged)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.btn)
        self.mainLayout.addWidget(self.lbShowImg)
        self.mainLayout.addWidget(self.slider)
        self.setLayout(self.mainLayout)

    def setImg(self):
        self.img = Image.open(QFileDialog.getOpenFileName(self, '选择图像', './', '图像文件(*.png *.jpg)')[0])
        # 设置图片: 指定路径
        # self.lbShowImg.setPixmap(QPixmap('D:\\WorkSpace\\Python\\pyside6_learn\\01_BV16d4y1s73t_202403\\resources\\Zelda.jpg'))
        # 设置图片：选择路径
        self.lbShowImg.setPixmap(self.toPixmap(self.img))

    def sliderValueChanged(self, val):
        # 模糊图像处理
        self.blurPic = self.img.filter(ImageFilter.GaussianBlur(val))
        self.lbShowImg.setPixmap(self.toPixmap(self.blurPic))

    def toPixmap(self, img):
        return ImageQt.toqpixmap(img).scaled(
            800, 800,           # 设置图片的最大宽高
            Qt.AspectRatioMode.KeepAspectRatio,         # 设置图片的缩放样式: 等比缩放
            Qt.TransformationMode.SmoothTransformation  # 设置变幻模式：平滑变换（速度慢些，但质量高些）
        )


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()
    window.show()

    app.exec()
